package com.sqsf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqsf.common.QueryPageParam;
import com.sqsf.common.Result;
import com.sqsf.entity.Student;
import com.sqsf.mapper.StudentMapper;
import com.sqsf.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public List<Student> getAll() {
        return studentMapper.selectList(null);
    }

    @Override
    public Result listPage(QueryPageParam queryPageParam) {
        Page<Student> userPage = new Page<>(queryPageParam.getCurrentPage(), queryPageParam.getPageSize());
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        //获取用户输入
        HashMap param = queryPageParam.getParam();
        //参数校验
        if(param != null){
            Object objName = param.get("name");
            if(!StringUtils.isEmpty(objName)){
                String name = (String) objName;
                wrapper.like(Student::getName, name);
            }
            Object objSex = param.get("sex");
            try {
                Integer sex = (Integer) objSex;
                wrapper.eq(Student::getSex, sex);
            } catch (Exception e) {
            }
        }
        Page<Student> page = studentMapper.selectPage(userPage, wrapper);

        return Result.suc(page.getRecords(), page.getTotal());
    }


    @Override
    public Result save(Student student) {
        student.setId(null);//防止代码污染
        if(studentMapper.insert(student) > 0){
            return Result.suc();
        }
        return Result.fail();
    }

    @Override
    public Result edit(Student student) {
        if(studentMapper.updateById(student) > 0){
            return Result.suc();
        }
        return Result.fail();
    }

    @Override
    public Result findById(String id) {
        Student student = studentMapper.selectById(id);
        return Result.suc(student);
    }
}
